package com.zj.sixtyDayChallenge.list;

/**
 * @program: algorithm
 * @description: 移除链表元素
 * 203 remove-linked-list-elements
 * @author: Zhang Bo
 * @create: 2023-02-06 14:30:41
 **/
public class RemoveLinkedListElements {
    public static void main(String[] args) {
        Solution solution = new RemoveLinkedListElements().new Solution();
    }
    //leetcode submit region begin(Prohibit modification and deletion)


    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    class Solution {
        /**
         * 前置指针还是比较重要的，很多链表的题目都需要前置指针去处理
         *
         * @param head
         * @param val
         * @return
         */
        public ListNode removeElements(ListNode head, int val) {

            //预设一个前置指针
            //因为要删除该元素，那么就需要知道前一个元素
            //让前一个元素指向下下个元素
            ListNode headNode = new ListNode(0);

            //这种方式还很好的解决了不同单独处理头结点的问题
            //对于链表来说，真是个不错的方法呢，嘻嘻
            headNode.next = head;

            ListNode node = headNode;

            while (node.next != null) {
                if (node.next.val == val) {
                    node.next = node.next.next;
                } else {
                    node = node.next;
                }
            }
            return headNode.next;
        }


        public ListNode removeEle(ListNode head, int val) {
            ListNode pre = new ListNode(0);

            pre.next = head;
            ListNode node = pre;
            while (node.next != null) {
                if (node.next.val == val) {
                    node.next = node.next.next;
                } else {
                    node = node.next;
                }
            }
            return pre.next;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}